package net.vkits.controller;

import net.vkits.admin.application.PostApplicationService;
import net.vkits.admin.domain.model.Post;
import net.vkits.admin.domain.model.SubPost;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by ethan-liu on 2017/2/7.
 */
@Controller
@RequestMapping("/subPosts")
public class SubPostsController {
    private static final Logger logger = LoggerFactory.getLogger(SubPostsController.class);

    @Resource
    private PostApplicationService postApplicationService;

    @RequiresPermissions("system:sys_role:list")
    @RequestMapping(value ="/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Page<SubPost> getSubPosts(@PathVariable Long id) {
        Post post = postApplicationService.getPost(id);
        Set<SubPost> subPosts = post.getSubPosts();
        List<SubPost> subPostList = new ArrayList<>();
        subPostList.addAll(subPosts);
        logger.info("size is: {}", subPosts.size());
        return new PageImpl<>(subPostList);
    }

    @RequiresPermissions("system:sys_role:add")
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String addSubPost(@RequestBody SubPost subPost) {
        logger.info("add SubPost: {}", subPost);
        postApplicationService.addSubPost(subPost);
        return "done";
    }

    @RequiresPermissions("system:sys_role:del")
    @RequestMapping(value ="/{id}/sub/{subId}", method = RequestMethod.DELETE)
    @ResponseBody
    public String delSubPost(@PathVariable Long id, @PathVariable Long subId) {
        logger.info("del SubPost id: {}", id);
        logger.info("del SubPost subId: {}", subId);
        postApplicationService.delSubPost(id, subId);
        return "done";
    }
}
